<?php
declare (strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;

class RaffleRecord extends Base
{
    protected function user(): object
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,code,nickname,mobile,photo');
    }

    public static function submit($user, $system): array
    {
        parent::startTrans();
        try {
            if (!$system['raffle_open']) {
                throw new \Exception('抽奖功能暂时关闭');
            }
            if ($system['raffle_amount'] > $user->assets->currency) {
                throw new \Exception(get_pay_way('currency') . '账户余额不足');
            }
            $list = RafflePrize::getPrize();
            if (!$list) {
                throw new \Exception('数据丢失了，请尝试刷新页面！');
            }
            Target::Account()->basics($user->id, 'currency', $system['raffle_amount'], '抽奖', '-')
                ->createNormal();
            $keys = self::get_rand($list);
            $prize = $list[$keys];
            if ($prize['id'] != 1) {
                $msg = '恭喜您获得';
                if ($prize['amount'] > 0) {
                    Target::Account()->basics($user->id, 'bonus', $prize['amount'], '中奖', '+')
                        ->createNormal();
                }
            } else {
                $msg = '很遗憾，再接再厉！';
            }
            parent::create([
                'uid' => $user->id,
                'title' => $prize['title'],
                'icon' => $prize['icon'],
                'amount' => $prize['amount']
            ]);

            parent::commit();
        } catch (\Exception $e) {
            parent::rollback();

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        return ['code' => 1, 'msg' => $msg, 'data' => $prize];
    }

    public static function get_rand($arr): int
    {
        $result = 0;
        $proArr = [];
        foreach ($arr as $k => $val) {
            $proArr[$k] = $val['odds'] * 100;
        }
        $proSum = (int)array_sum($proArr);
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= (int)$proCur;
            }
        }

        return $result;
    }
}